<?php
require_once 'player.php';

class PlayerList extends Model {
  const PLAYER_XPATH = "/players/player";

  private $players;

  public function __construct() {
    $this->players = array();
  }

  public function loadFromFile($fileName = FILEPATH_PLAYERS, $unlink = FALSE) {
    $this->load->helper('file');
    $doc = new DOMDocument('1.0', 'utf-8');

    $tClubFile = read_file($fileName);
    if (!$tClubFile) {
      log_message('error','Unable to open players file: '.$fileName);
      return false;
    }

    $tDocument = $doc->loadXML($tClubFile);
    if (!$tDocument) {
      log_message('error','The players file is not valid XML!');
      return false;
    } else {
      $this->players = array();

      $xPath = new DOMXPath($doc);
      $qResult = $xPath->query(PlayerList::PLAYER_XPATH);

      foreach ($qResult as $result) {
        $player = new Player($this->db);
        $player->loadFromNode($result);
        array_push($this->players, $player);
      }
    }
    if ($unlink) {
      unlink($fileName);
    }
    return true;
  }

  public function downloadOwnPlayers() {
    $userName = $this->session->userdata('username');
    $password = $this->session->userdata('password');
    $isVip = $this->session->userdata('isVIP');

    $this->load->helper('file');
    $this->load->helper('curl');
    $this->load->helper('crypt');

    $URL = 'http://www.freekick.org/public/getdata.php?getdata=ownplayers&datatype=xml'.
        '&username='.$userName.'&password='.decrypt($password).'&vip='.$isVip;

    $playersFile = read_url($URL);
    if (!$playersFile) {
      log_message('error','Unable to open club URL!');
      return false;
    }

    $tmpfname = tempnam(DIRPATH_TEMP, "play");

    $xmlFile = write_file($tmpfname,$playersFile);

    if (!$xmlFile) {
      log_message('error','Unable to open club file!!');
      return false;
    }

    log_message('info','Player xml created!');
    return $tmpfname;
  }

  public function insertToDB() {
    $clubId = $this->session->userdata['clubId'];
    $this->markRemovedPlayers();

    foreach ($this->players as $player) {
      $this->db->where('id',$player->getID());
      $this->db->from('player');
      $count = $this->db->count_all_results();

      if ($count == 0) {
        $player->insertNewToDB($clubId);
      } else {
        $player->amendOldInDB();
      }
    }
  }

  public function markRemovedPlayers() {
    $clubId = $this->session->userdata['clubId'];

    $this->db->select('id');
    $this->db->where('clubId',$clubId);
    $query = $this->db->get('player');

    if (!$query) {
      log_message('error', 'No Player found in the database!');
    }

    $dataBase = array();

    foreach ($query->result() as $row) {
      array_push($dataBase, $row->id);
    }

    $playerList = array();

    foreach ($this->players as $player) {
      array_push($playerList, $player->getID());
    }

    $diffs = array_diff($dataBase, $playerList);

    foreach ($diffs as $diff) {
      $this->db->set('isDeleted',TRUE);
      $this->db->where('id',$diff);
      $query = $this->db->update('player');

      if (!$query) {
        log_message('error', 'Error during deleted players update!');
      } else {
        log_message('info','Player record ('.$diff.') was marked as deleted in the database%');
      }
    }
  }

  public function loadFromDB($clubId) {

    $conn = &ADONewConnection('mysqli');
    $conn->PConnect(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE);
    $conn->SetCharSet("utf8");

    $stmt = $conn->Prepare('SELECT `playerId` FROM `player` WHERE `clubId` = ? and `isDeleted` = 0');
    $rs=$conn->Execute($stmt,array($clubId));

    if (!$rs) {
      $logger = Logger::getInstance();
      $logger->log($conn->ErrorMsg(), Logger::ERR);
    }

    if ($rs->RecordCount()==0) {
      $logger = Logger::getInstance();
      $logger->log("No player for club({$clubId}) not found in database.", Logger::ERR);;
    } else {
      $this->players = array();
      while ($result = $rs->FetchRow()) {
        $tmpPlayer = new Player();
        $tmpPlayer->loadFromDB($conn,$result['playerId']);
        array_push($this->players,$tmpPlayer);
      }
    }

    $conn->Close();
  }
}
?>
